package com.elminster.common.db.manager;

import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

import com.elminster.common.db.annotation.DAO;

public class DAOSupportManager {

	private static DAOSupportManager instance_ = new DAOSupportManager();
	private Map<Class<?>, Object> daoCache = new HashMap<Class<?>, Object>();
	
	private DAOSupportManager() {}
	
	public static DAOSupportManager getInstance() {
		return DAOSupportManager.instance_;
	}
	
	public Object getDAO(Class<?> clazz) {
		if (null == clazz) {
			return null;
		}
		if (!isDAOClass(clazz)) {
			return null;
		}
		Object obj = daoCache.get(clazz);
		if (null == obj) {
			DAOInvokeHandler handler = new DAOInvokeHandler();
			obj = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] {clazz}, handler);
			daoCache.put(clazz, obj);
		}
		return obj;
	}

	private boolean isDAOClass(Class<?> clazz) {
		return null != clazz.getAnnotation(DAO.class);
	}
}
